const {model: articleModel} = require('../models/article')
const {model: userModel} = require('../models/user')

/**
 * 新增评论数目
 * @param params    传参 articleId
 * @returns {Promise<object>} 结果
 */
function setArticleCommentCount(params) {
    return new Promise((resolve, reject) => {
        articleModel.findOneAndUpdate({articleId: params.articleId}, {$inc: {commentCount: 1}}, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '增加评论成功'})
            } else {
                reject({code: 0, data: null, msg: err.message})
            }
        })
    })
}

/**
 * 用户内记录评论的文章
 * @param params 传参 articleId userId
 * @returns {Promise<object>} 结果
 */
function setUserCommentArticles(params){
    return new Promise((resolve, reject) => {
        const filter = {id: params.userId}
        const updateData = {
            $push: {
                commentArticles: {
                    articleId: params.articleId,
                    craeteTime: Date.now()
                }
            }
        }
        userModel.findOneAndUpdate(filter, updateData, (err, docs) => {
            if (!err) {
                resolve({code: 1, data: null, msg: '记录评论的文章成功'})
            } else {
                reject({code: 0, data: null, msg: err.message})
            }
        })
    })
}

module.exports = {setArticleCommentCount, setUserCommentArticles}